from flask import Flask,request,send_from_directory
import os
import json
import pymysql
import time
import contextlib
@contextlib.contextmanager
def mysql(host='127.0.0.1', port=53306, user='root', passwd='VWZ5qtYI3VpA7#DI', db='phone_api',charset='utf8'):
  conn = pymysql.connect(host=host, port=port, user=user, passwd=passwd, db=db, charset=charset)
  cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
  try:
    yield cursor
  finally:
    conn.commit()
    cursor.close()
    conn.close()
app=Flask(__name__)

@app.route("/login_first",methods=["GET"])
def firstlogin():
    return_dict= {'return_code': '200', 'return_info': 'success', 'result': False}
    if request.args is None:
        return_dict['return_code'] = '5004'
        return_dict['return_info'] = 'args is null'
        return json.dumps(return_dict, ensure_ascii=False)
    get_data=request.args.to_dict()
    phonenumber=get_data.get('phonenumber')
    kouling=get_data.get('kouling')
    return_dict['result']=judge_firstlogin(phonenumber,kouling)
    return json.dumps(return_dict, ensure_ascii=False)

@app.route("/updatetime",methods=["GET"])
def updatetime():
    return_dict= {'return_code': '200', 'return_info': 'success', 'result': False}
    if request.args is None:
        return_dict['return_code'] = '5004'
        return_dict['return_info'] = 'args is null'
        return json.dumps(return_dict, ensure_ascii=False)
    get_data=request.args.to_dict()
    kouling=get_data.get('kouling')
    if kouling=='knDmIXleinbu91m6':
        return_dict['result']=get_updatetime()
    return json.dumps(return_dict, ensure_ascii=False)

@app.route("/search",methods=["GET"])
def search():
    return_dict= {'return_code': '200', 'return_info': 'success', 'result': False}
    if request.args is None:
        return_dict['return_code'] = '5004'
        return_dict['return_info'] = 'args is null'
        return json.dumps(return_dict, ensure_ascii=False)
    get_data=request.args.to_dict()
    query=get_data.get('query')
    insert_query(query)
    return_dict['result']=search_all(query)
    return json.dumps(return_dict, ensure_ascii=False)

@app.route("/getlist",methods=["POST"])
def getphone():
    return_dict= {'return_code': '200', 'return_info': 'success', 'result': False}
    if request.get_data() is None:
        return_dict['return_code'] = '5004'
        return_dict['return_info'] = 'args is null'
        return json.dumps(return_dict, ensure_ascii=False)
    get_Data=request.get_data()
    get_Data=json.loads(get_Data)
    kouling=get_Data.get('kouling')
    if kouling=='knDmIXleinbu91m6':
        return_dict['result']=getphonelist()
    return json.dumps(return_dict, ensure_ascii=False)

@app.route("/download")
def download_file():
    directory = os.getcwd()
    print(directory)
    return send_from_directory(directory,'app.apk', as_attachment=True)

def judge_firstlogin(phonenumber,kouling):
    with mysql() as cursor:
        row_count = cursor.execute("select * from userlist WHERE phoneNumber = %s"%(phonenumber))
        row_1 = cursor.fetchone()
    nowtime = time.strftime("%Y%m%d")
    if row_1 is not None:
        if kouling==nowtime:
            insert_login(phonenumber)
            return 'yes'
        else:
            return 'no'
    else:
        return 'no'
def get_updatetime():
    with mysql() as cursor:
        row_count = cursor.execute("select * from updatetime")
        row_1 = cursor.fetchone()
    update_time = row_1['update_time']
    return update_time.strftime("%Y-%m-%d %H:%M:%S")
def insert_login(phonenumber):
    with mysql() as cursor:
        create_time=time.strftime("%Y%m%d%H%M%S")
        cursor.execute("insert into login (phone,create_time) values (%s,%s)"%(phonenumber,create_time))
def getphonelist():
    with mysql() as cursor:
        row_count = cursor.execute("select * from userlist WHERE is_app=1 ORDER BY userName")
        row_list = cursor.fetchall()
    userCompany_list = ['一级单位', '二级单位1', '二级单位2', '二级单位3','二级单位4', '二级单位5', '二级单位6', '二级单位7']
    userCompany_py=[]
    for userCompany in userCompany_list:
        belong_company=[]
        py_index=[]
        py_user=[]
        for row in row_list:
            if userCompany==row['userCompany']:
                line_dict={'userName': row['userName'], 'phoneNumber': row['phoneNumber'], 'shortNumber': row['shortNumber'], 'pinYin': row['pinYin']}
                belong_company.append(line_dict)
        for belong in belong_company:
            py_index.append(belong['pinYin'])
        new_index = list(set(py_index))
        new_index.sort()
        for index in new_index:
            index_user=[]
            for belong in belong_company:
                if index==belong['pinYin']:
                    line_dict={'userName': belong['userName'], 'phoneNumber': belong['phoneNumber'], 'shortNumber': belong['shortNumber']}
                    index_user.append(line_dict)
            index_dict = {'py':index,'index_user':index_user}
            py_user.append(index_dict)
        belong_index = {'userCompany':userCompany,'py_user':py_user}
        userCompany_py.append(belong_index)
    return userCompany_py
def search_all(query):
    result=[]
    with mysql() as cursor:
        sql1 = "select * from userlist WHERE phoneNumber like '%%{}%%' and is_app=1 ORDER BY userName".format(query)
        row_count1 = cursor.execute(sql1)
        row_1 = cursor.fetchall()
        sql2 = "select * from userlist WHERE shortNumber like '%%{}%%' and is_app=1 ORDER BY userName".format(query)
        row_count2 = cursor.execute(sql2)
        row_2 = cursor.fetchall()
        sql3 = "select * from userlist WHERE userName like '%%{}%%' and is_app=1 ORDER BY userName".format(query)
        row_count3 = cursor.execute(sql3)
        row_3 = cursor.fetchall()
    result.extend(row_1)
    result.extend(row_2)
    result.extend(row_3)
    return result
def insert_query(query):
    with mysql() as cursor:
        search_time=time.strftime("%Y%m%d%H%M%S")
        cursor.execute("insert into searchquery (squery,search_time) values ('%s',%s)"%(query,search_time))
if __name__ == "__main__":
    app.run()     